#ifndef SETTINGSCONTROLLER_H
#define SETTINGSCONTROLLER_H

#include <QObject>
#include <QString>
#include "utils/Config.h"
#include "utils/Logger.h"
#include "services/DatabaseService.h"

/**
 * @brief 设置控制器
 * @details Controller 层，协调系统设置业务流程：
 *          - 系统配置管理（调用 Config）
 *          - 数据库维护（调用 DatabaseService）
 *          - 日志管理（调用 Logger）
 *          - 应用信息查询
 *          - 暴露 Q_INVOKABLE 方法给 QML 调用
 */
class SettingsController : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString appVersion READ appVersion CONSTANT)
    Q_PROPERTY(QString appName READ appName CONSTANT)
    Q_PROPERTY(qint64 databaseSize READ databaseSize NOTIFY databaseSizeChanged)
    Q_PROPERTY(bool autoCleanupEnabled READ autoCleanupEnabled WRITE setAutoCleanupEnabled NOTIFY autoCleanupEnabledChanged)

public:
    explicit SettingsController(QObject *parent = nullptr);
    ~SettingsController();

    // 设置依赖对象
    void setConfig(Config *config);
    void setLogger(Logger *logger);
    void setDatabaseService(DatabaseService *dbService);

    // 属性访问器
    QString appVersion() const { return "1.0.0"; }
    QString appName() const { return "Modbus TCP Monitor"; }
    qint64 databaseSize() const;
    bool autoCleanupEnabled() const;
    void setAutoCleanupEnabled(bool enabled);

    // === 通用配置 ===
    Q_INVOKABLE int getPollInterval() const;
    Q_INVOKABLE bool setPollInterval(int intervalMs);

    Q_INVOKABLE int getRealtimeDataRetentionDays() const;
    Q_INVOKABLE bool setRealtimeDataRetentionDays(int days);

    Q_INVOKABLE int getMinuteDataRetentionDays() const;
    Q_INVOKABLE bool setMinuteDataRetentionDays(int days);

    Q_INVOKABLE int getHourDataRetentionDays() const;
    Q_INVOKABLE bool setHourDataRetentionDays(int days);

    Q_INVOKABLE QString getCleanupTime() const;
    Q_INVOKABLE bool setCleanupTime(const QString &time);

    // === 报警阈值配置 ===
    Q_INVOKABLE double getTempWarningThreshold() const;
    Q_INVOKABLE bool setTempWarningThreshold(double value);

    Q_INVOKABLE double getTempCriticalThreshold() const;
    Q_INVOKABLE bool setTempCriticalThreshold(double value);

    Q_INVOKABLE double getPressureWarningThreshold() const;
    Q_INVOKABLE bool setPressureWarningThreshold(double value);

    Q_INVOKABLE double getPressureCriticalThreshold() const;
    Q_INVOKABLE bool setPressureCriticalThreshold(double value);

    Q_INVOKABLE double getFlowWarningThreshold() const;
    Q_INVOKABLE bool setFlowWarningThreshold(double value);

    // === 数据库维护 ===
    Q_INVOKABLE bool optimizeDatabase();
    Q_INVOKABLE bool vacuumDatabase();
    Q_INVOKABLE bool analyzeDatabase();
    Q_INVOKABLE bool backupDatabase(const QString &backupPath);
    Q_INVOKABLE bool restoreDatabase(const QString &backupPath);

    // === 数据清理 ===
    Q_INVOKABLE bool clearOldRealtimeData();
    Q_INVOKABLE bool clearOldMinuteData();
    Q_INVOKABLE bool clearOldHourData();
    Q_INVOKABLE bool clearAllHistoryData();

    // === 数据库信息 ===
    Q_INVOKABLE int getRealtimeDataCount() const;
    Q_INVOKABLE int getMinuteDataCount() const;
    Q_INVOKABLE int getHourDataCount() const;
    Q_INVOKABLE int getAlarmCount() const;
    Q_INVOKABLE int getDeviceCount() const;
    Q_INVOKABLE QString getDatabasePath() const;

    // === 日志管理 ===
    Q_INVOKABLE bool clearOperationLogs(int daysToKeep = 30);
    Q_INVOKABLE int getOperationLogCount() const;
    Q_INVOKABLE QString getLogFilePath() const;
    Q_INVOKABLE bool openLogFile();

    // === 系统信息 ===
    Q_INVOKABLE QString getSystemInfo() const;
    Q_INVOKABLE QString getQtVersion() const;
    Q_INVOKABLE QString getBuildDate() const;

    // === 配置导入导出 ===
    Q_INVOKABLE bool exportConfig(const QString &filePath);
    Q_INVOKABLE bool importConfig(const QString &filePath);
    Q_INVOKABLE bool resetToDefaultConfig();

    // === 刷新数据库大小 ===
    Q_INVOKABLE void refreshDatabaseSize();

signals:
    // 属性变化信号
    void databaseSizeChanged();
    void autoCleanupEnabledChanged();

    // 配置变更信号
    void configChanged(const QString &key, const QVariant &value);

    // 数据库维护信号
    void databaseOptimized();
    void databaseBackupCompleted(const QString &backupPath);
    void databaseRestored();

    // 数据清理信号
    void dataCleaned(int recordsRemoved);

    // 错误信号
    void errorOccurred(const QString &error);

private:
    // 验证阈值有效性
    bool validateThreshold(double value, const QString &name);

    // 验证时间格式 HH:MM
    bool validateTimeFormat(const QString &time);

    // 获取表记录数
    int getTableRecordCount(const QString &tableName) const;

    // 清理旧数据
    bool cleanOldData(const QString &tableName, int daysToKeep);

private:
    Config *m_config;                   // 配置管理器
    Logger *m_logger;                   // 日志管理器
    DatabaseService *m_databaseService; // 数据库服务
};

#endif // SETTINGSCONTROLLER_H
